public class NextGreaterElement2 {

    public static void main(String[] args) {
        NextGreaterElement2 nextGreaterElement2 = new NextGreaterElement2();
        System.out.println(nextGreaterElement2.nextGreaterElement(230241));
    }

    public int nextGreaterElement1(int n) {
        if (n < 10) return -1;
        String s = n + "";
        char[] chars = s.toCharArray();
        int index = chars.length - 1;
        for (int i = chars.length - 2; i >= 0; i--) {
            if (chars[i] < chars[i + 1]) {
                index = i;
                break;
            }
        }
        if (index == chars.length - 1) return -1;
        int target = chars.length - 1;
        for (int i = chars.length - 1; i >= 0; i--) {
            if (chars[i] > chars[index]) {
                target = i;
                break;
            }
        }
        char temp = chars[index];
        chars[index] = chars[target];
        chars[target] = temp;
        int l = index + 1;
        int r = chars.length - 1;
        while (l <= r) {
            temp = chars[l];
            chars[l] = chars[r];
            chars[r] = temp;
            ++l;
            --r;
        }
        long ans = Long.parseLong(new String(chars));
        return ans > Integer.MAX_VALUE ? -1 : (int) ans;
    }

    public int nextGreaterElement(int n) {
        char[] chars = (n + "").toCharArray();
        int m = chars.length;
        int i = m - 2;
        while (i >= 0 && chars[i] >= chars[i + 1]) ++i;
        if (i < 0) return -1;
        int j = m - 1;
        while (j >= i && chars[j] <= chars[i]) --j;
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
        int l = i + 1;
        int r = m - 1; 
        while (l <= r) {
            temp = chars[l];
            chars[l] = chars[r];
            chars[r] = temp;
            ++l;
            --r;
        }
        long ans = Long.parseLong(new String(chars));
        return ans > Integer.MAX_VALUE ? -1 : (int) ans;
    }
}
